package org.csu.mypetstore.persistence.Impl;


import org.csu.mypetstore.domain.Log;
import org.csu.mypetstore.persistence.DBUtil;
import org.csu.mypetstore.persistence.LogDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class LogDAOImpl implements LogDAO {
    private static final String INSERT_LOG = "INSERT INTO LOG (USERID, DATE, INFO) VALUES (?, ?, ?)";

    private static final String GET_LOGS_BY_USERNAME = "SELECT  DATE, INFO FROM LOG WHERE USERID = ? ";

    //添加log信息
    @Override
    public boolean addLog(Log log) {
        boolean flag = false;

        try{
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(INSERT_LOG);
            preparedStatement.setString(1,log.getUsername());
            preparedStatement.setString(2,log.getDate());
            preparedStatement.setString(3,log.getInfo());

            int row = preparedStatement.executeUpdate();
            if(row == 1){
                flag = true;
                System.out.println("插入一项到log" + log.getUsername()+log.getDate()+log.getInfo());
            }
            DBUtil.closePreparedStatement(preparedStatement);
            DBUtil.closeConnection(connection);
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }


    //根据名字获取日志信息
    @Override
    public List<Log> getLogsByUsername(String username) {
        List<Log> logList = new ArrayList<>();

        try {
            Connection connection = DBUtil.getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(GET_LOGS_BY_USERNAME);
            preparedStatement.setString(1,username);
            ResultSet resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                Log log = new Log();
                log.setDate(resultSet.getString(1));
                log.setInfo(resultSet.getString(2));
                logList.add(log);

            }
            DBUtil.closeResultSet(resultSet);
            DBUtil.closePreparedStatement(preparedStatement);
            DBUtil.closeConnection(connection);

        }catch (Exception e){
            e.printStackTrace();
        }
        return logList;
    }
}
